<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import {reactive, ref, watch} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {loginByPasswordAPI, loginBySMSAPI, sendSMSAPI} from '@/apis/login'
import {useUserStore} from '@/stores/user'
import router from "@/router/index.js";

const ruleFormRef = ref<FormInstance>()


const validateAccount = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!(value.length>=6&&value.length<=14)) {
    callback(new Error("密码长度为6-14个字符"))
  } else {
    callback()
  }
}

const validatePhoneNumber = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (value.length!==11) {
    callback(new Error("手机号格式不对"))
  } else {
    callback()
  }
}

const validateCaptcha = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入4位验证码'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  account:'',
  password: '',
  phoneNumber:'',
  captcha:''
})


const rules = reactive<FormRules<typeof ruleForm>>({
  account: [{ validator: validateAccount, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  phoneNumber: [{ validator: validatePhoneNumber, trigger: 'blur' }],
  captcha: [{ validator: validateCaptcha, trigger: 'blur' }],

})

//默认登录方式为密码登录
const loginMode = ref('password')

watch(loginMode,(newMode,oldMode)=>{
  if(newMode==='captcha'){
    ruleForm.account=''
    ruleForm.password=''
  }else if(newMode==='password'){
    ruleForm.phoneNumber=''
    ruleForm.captcha=''
  }
})


const loginByPassword=async ()=>{
  const res= await loginByPasswordAPI(ruleForm)
  if(res.code==200){
    console.log('用户信息',res.data)
    //保存用户信息
    await useUserStore().alterUserInfo(res.data)

    // 根据用户身份判断跳转路径
    const userStore = useUserStore()
    // 假设用户信息中用role字段区分身份，管理员为'admin'
    if (userStore.userInfo?.role === 'admin') {
      // 管理员跳转到/admin
      await router.replace('/admin')
    } else {
      // 普通用户跳转到首页
      await router.replace('/homePage')
    }
  }else{
    ElMessage({
      message: res.message,
      type: res.code===200?'success':'error',
      plain: true,
    })
  }
  console.log(res.message)
}

//短信验证码登录
const loginBySMS=async ()=>{
  const res= await loginBySMSAPI(ruleForm)
  if(res.code==200){
    console.log('用户信息',res.data)
    //保存用户信息
    await useUserStore().alterUserInfo(res.data)

    // 根据用户身份判断跳转路径
    const userStore = useUserStore()
    if (userStore.userInfo?.role === 'admin') {
      await router.replace('/admin')
    } else {
      await router.replace('/homePage')
    }
  }else{
    ElMessage({
      message: res.message,
      type: 'error',
      plain: true,
    })
  }
}

const seconds=ref(false)
// 创建定时器
let intervalId
//发送短信验证码
async function sendMSM() {
  if (ruleForm.phoneNumber.length===11&&seconds.value===false){
    try {
      const res = await sendSMSAPI(ruleForm.phoneNumber)
      if(res.code===200){
        seconds.value=60
        //启动定时器
        intervalId = setInterval(() => {
          seconds.value--;
        }, 1000); // 1000毫秒，即1秒
        
        ElMessage({
          message: '验证码发送成功',
          type: 'success',
          plain: true,
        })
      }else{
        ElMessage({
          message: res.message || '验证码发送失败',
          type: 'error',
          plain: true,
        })
      }
    } catch (error) {
      ElMessage({
        message: '验证码发送失败，请重试',
        type: 'error',
        plain: true,
      })
    }
  }
}

watch(seconds,(newValue,oldValue)=>{
  if(seconds.value===0){
    //清除定时器，防止内存泄漏
    clearInterval(intervalId)
    seconds.value=false
  }
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //根据登录方式选择不同的登录方法
      if(loginMode.value === 'password'){
        loginByPassword()
      }else if(loginMode.value === 'captcha'){
        loginBySMS()
      }
    } else {
      console.log('error submit!')
    }
  })
}

</script>

<template>
  <div class="loginPage">
    <div class="loginBox">

      <div style="">
        <el-radio-group v-model="loginMode" size="large" fill="#fff" text-color="#01b808">
          <el-radio-button label="密码登录" value="password" />
          <el-radio-button label="短信登陆" value="captcha" />
        </el-radio-group>
      </div>

      <div class="form">

        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
        >

          <template v-if="loginMode==='password'">
            <el-form-item label="" :prop="loginMode==='password'?'account':null">
              <el-input
                  class="inputArea"
                  v-model="ruleForm.account"
                  placeholder="账号名/手机号"
                  autocomplete="off"
              />
            </el-form-item>

            <el-form-item label="" :prop="loginMode==='password'?'password':null">
              <el-input
                  class="inputArea"
                  v-model="ruleForm.password"
                  placeholder="密码"
                  type="password"
                  autocomplete="off"
              />
            </el-form-item>

            <el-form-item style="margin-top: 1px;margin-bottom: 5px" >
              <span style="margin-left: auto" class="findPassword">忘记密码</span>
            </el-form-item>

          </template>

          <template v-else-if="loginMode==='captcha'">
            <el-form-item label="" :prop="loginMode==='captcha'?'phoneNumber':null">
              <el-input
                  class="inputArea"
                  v-model="ruleForm.phoneNumber"
                  placeholder="手机号"
                  autocomplete="off"
              />
            </el-form-item>

            <el-form-item label="" :prop="loginMode==='captcha'?'captcha':null">
              <el-input
                  class="inputArea"
                  style="margin-bottom: 20px"
                  v-model="ruleForm.captcha"
                  placeholder="验证码"
                  autocomplete="off"
              >
                <template #suffix>
                <span class="send-sms-btn"
                      :style="{'--textColor':ruleForm.phoneNumber.length===11&&!seconds?'rgb(1, 184, 8)':null,
                      '--hoverCursor':ruleForm.phoneNumber.length===11&&!seconds?'pointer':'no-drop',
                      '--hoverColor':ruleForm.phoneNumber.length===11&&!seconds?'rgb(1, 184, 8)':null,}"
                      @click="sendMSM"
                >{{!seconds?'发送验证码':seconds+'s后重新获取'}}</span>
                </template>
              </el-input>

            </el-form-item>
          </template>


          <el-form-item>
            <el-button
                class="loginBtn"
                type="primary"
                @click="submitForm(ruleFormRef)">
              登&nbsp&nbsp录
            </el-button>

          </el-form-item>

          <el-form-item >
            <img src="@/assets/qq.png" style="width: 25px" alt=""><span>&nbspQQ</span>&nbsp&nbsp&nbsp
            <img src="@/assets/weixin.png" style="width: 25px" alt=""><span>&nbsp微信</span>
            <span style="margin-left: auto" class="findPassword" @click="router.push('/register')">立即注册</span>
          </el-form-item>
        </el-form>


      </div>
      <div class="codeBox">
        <label style="font-size: 20px;font-weight: bold;margin-bottom: 10px" >手机扫码登陆</label>
        <div style="
      width: 170px;
      height: 170px;
      margin-bottom: 30px;
      border: rgba(219,225,231,0.64) 1px solid;
      padding: 20px;
      display: flex;
      justify-content: center;
      align-items: center;">
          <img src="@/assets/loginCode.png" alt="">
        </div>

        <span style="font-size: 14px;color:#666666;font-family: Arial,Verdana,宋体">打开手机，扫描二维码</span>

      </div>

    </div>
  </div>
</template>

<style scoped lang="less">
.loginPage{
  width: 100%;
  height: 900px;

  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  background-image:linear-gradient(135deg,#C2FFD8 10%,#465EFB 100%)
  //background-color:  #F5F6FA;
}

.loginBox{
  width: 1000px;
  height: 470px;

  border-radius: 15px;
  background-color: #ffffff;

  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  align-content: center;
}

.codeBox{
  height: 400px;
  width: 400px;
  //background-color: #ea7128;

  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}


label{
  font-size: 20px;
  font-weight: bold;
  color:#1A1A1A;
}

.form{
  height: 270px;
  width: 600px;


  background-color: white;

  display: flex;
  justify-content: center;
  align-items: center;
}


.send-sms-btn{
  color:var(--textColor);
  border: none;
  background-color: rgba(255, 255, 255, 0);
  font-size: 14px;
}

.send-sms-btn:hover{
  color:var(--hoverColor);
  cursor: var(--hoverCursor);
}

.findPassword:hover{
  color: rgb(1, 184, 8);
  cursor: pointer;
}
.findPassword:hover::after{

}


.inputArea{
  width: 370px;
  height: 45px;
  :deep(.el-input__wrapper){
    background-color: rgb(162 175 185 / 9%);
    box-shadow: 0 0 0 0 inset;
    border-radius: 10px;
  }
}
.loginBtn{
  width: 100%;
  height: 45px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: bold;
  background-color: #39bf3e;
  color: white;
  border: none;
}
.el-radio-button{
  :deep(.el-radio-button__inner){
    color: #1B1B1B;
    font-size: 20px;
    font-weight: bold;
    border: none;
  }
}
</style>
